//
//  ViewController.swift
//  Combinestagram
//
//  Created by infoware on 2018/5/24.
//  Copyright © 2018年 infoware. All rights reserved.
//

import UIKit
import RxSwift

class ViewController: UIViewController {
    
    @IBOutlet weak var imagePreview: UIImageView!
    
    @IBOutlet weak var buttonClear: UIButton!
    
    @IBOutlet weak var buttonSave: UIButton!
    
    @IBOutlet weak var itemAdd: UIBarButtonItem!
    
    var images = Variable<[UIImage]>([])
    
    let bag = DisposeBag()
    
    private var imageCache = [Int]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        let newImages = images.asObservable().share()
        
      newImages
            .throttle(0.5, scheduler: MainScheduler.instance)
            .subscribe(onNext: { [weak self] photos in
            guard let preview = self?.imagePreview else { return }
            preview.image = UIImage.collage(images: photos,
                                            size: preview.frame.size)
        })
            .disposed(by: bag)
        
         newImages
            .subscribe(onNext: {[weak self] photos in
            self?.updateUI(photos: photos)
        })
            .disposed(by: bag)
    }
    
    private func updateUI(photos:[UIImage]){
        buttonSave.isEnabled = photos.count > 0 && photos.count % 2 == 0
        buttonClear.isEnabled = photos.count > 0
        itemAdd.isEnabled = photos.count < 6
        title = photos.count > 0 ? "\(photos.count) photos" : "Collage"
    }
    
    
    @IBAction func actionClear(_ sender: UIButton) {
        images.value = []
        imageCache = []
        
    }
    
    @IBAction func actionSave(_ sender: UIButton) {
        guard let image = imagePreview.image else { return }
        PhotoWriter.save(image)
            .asSingle()
            .subscribe(onSuccess: { [weak self] id in
                self?.showMessage("Saved with id: \(id)")
                //UIButton 没用
                self?.actionClear(UIButton())
                }, onError: { [weak self] error in
                    self?.showMessage("Error", description: error.localizedDescription)
            })
            .disposed(by: bag)
    }
    
    @IBAction func actionAdd(_ sender: UIBarButtonItem) {
        // images.value.append(UIImage(named:("2.jpg"))!)
        
        let photosViewController = storyboard!.instantiateViewController(
            withIdentifier: "PhotosViewController") as! PhotosViewController
        
        let newPhotos = photosViewController.selectedPhotos.share()
        
        newPhotos
            .filter { newImage in
                return newImage.size.width > newImage.size.height
            }
            .takeWhile { [weak self] image in
                return (self?.images.value.count ?? 0) < 6
            }
            .filter({ [weak self] newImage  in
                let len = UIImagePNGRepresentation(newImage)?.count ?? 0
                guard self?.imageCache.contains(len) == false else {
                    return false
                }
                self?.imageCache.append(len)
                return true
            })
            .subscribe(onNext: { [weak self] newImage in
            guard let images = self?.images else { return }
            images.value.append(newImage)
            }, onDisposed: {
                print("completed photo selection")
        })
            .disposed(by: bag)
        
        
        newPhotos
            .ignoreElements()
            .subscribe(onCompleted: {[weak self] in
                self?.updateNavigationIcon()
            })
             .disposed(by: bag)
        

        
        navigationController?.pushViewController(photosViewController, animated: true)
    }
    
    private func updateNavigationIcon() {
        let icon = imagePreview.image?
            .scaled(CGSize(width: 22, height: 22))
            .withRenderingMode(.alwaysOriginal)
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: icon,
                                                           style: .done, target: nil, action: nil)
    }
    
    func showMessage(_ title:String, description:String? = nil){
        let alert = UIAlertController(title: title, message: description, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Close", style: .default, handler: { [weak self] _ in self?.dismiss(animated: true, completion: nil)}))
        present(alert, animated: true, completion: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
}

